<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class Sign extends Model
{

    

    

    // 表名
    protected $name = 'sign';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
	
	
	public function user() {
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}

    public function sign($userId) {
	    $setting = Db::name('signSetting')->find();
	
	    $this->startTrans();
	    try {
	    	
	    	$point = $setting ? $setting['sign_point'] : 0;
		
		    $res = $this->isUpdate(false)
			    ->save([
				    'user_id' => $userId,
				    'point' =>$point
			    ]);
		
		    if(!$res) {
			    throw new Exception('签到出错');
		    }
		
		    if($point > 0) {
		    	$user = \app\admin\model\User::get($userId);
		    	$userRes = Db::name('user')
				    ->where(['id' => $userId])
				    ->setInc('score', $point);
		    	
		    	if(!$userRes) {
		    		throw new Exception('添加用户积分出错');
			    }
		    	
		    	
			    $fundModel = new Funds();
			    
			    $fundRes = $fundModel->addRecord($userId, $point, $user['score'], $fundModel::ACCOUNT_TYPE_INTEGRAL, $fundModel::OPE_TYPE_PLUS, $fundModel::TYPE_SIGN);
			    
			    if(!$fundRes) {
			    	throw new Exception('添加积分记录出错');
			    }
		    }
		
		    $this->commit();
			
		    return [
			    'date' => date('Y-m-d'),
			    'point' => $point
		    ];
		
	    } catch (Exception $e) {
	    	return false;
	    }
    }
    







}
